/*
 * Copyright (c) 2020-2021, Bluetrum Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2020/12/10     greedyhao    The first version
 */

#include <rtthread.h>
#include "board.h"
#include "led_app.h"

#define DEVICE_NAME_TIMER1  "timer1"
rt_device_t       hw_time_dev;
rt_hwtimer_mode_t hwtimer_mode;     // 定时模式，单次定时/周期定时
rt_hwtimerval_t   hwtimerval;       // 超时值配置

rt_err_t timer1_timeout_cb(rt_device_t dev, rt_size_t size)
{
    rt_kprintf("This is ab32-vg1 board hwtimer1 test sample!\n");
    return RT_EOK;
}

rt_err_t hw_timer_test(void)
{
    rt_err_t ret = RT_EOK;

    // 查找设备
    hw_time_dev = rt_device_find(DEVICE_NAME_TIMER1);
    if (hw_time_dev == RT_NULL)
    {
        rt_kprintf("find %s failed\r\n",DEVICE_NAME_TIMER1);
        return RT_ERROR;
    }
    rt_kprintf("find %s success\n",DEVICE_NAME_TIMER1);

    // 打开设备(读写)
    rt_device_open(hw_time_dev, RT_DEVICE_OFLAG_RDWR);

    // 设置定时器工作模式（周期）
    hwtimer_mode = HWTIMER_MODE_PERIOD;
    rt_device_control(hw_time_dev, HWTIMER_CTRL_MODE_SET, &hwtimer_mode);

    // 设置超时回调函数
    rt_device_set_rx_indicate(hw_time_dev, timer1_timeout_cb);

    // 超时值配置
    hwtimerval.sec = 1;
    hwtimerval.usec = 0;    // ms
    rt_device_write(hw_time_dev, 0, &hwtimerval, sizeof(hwtimerval));

    return RT_EOK;
}

int main(void)
{
    rt_kprintf("Hello, ab32-vg1\n");
    led_app();
    hw_timer_test();
    return 0;
}
